import re
from untils.fileprocess import opredict
reg = ""

def rreplace(self, old, *max):
    count = len(self)
    if max and str(max[0]).isdigit():
        count = max[0]
    t = self.rsplit(old, 1)
    return "".join(t).rstrip()

def splitbyreg(s):
    re_list = re.split(r'[.|\?|!]', s)
    if len(re_list) > 1:
        return re_list
    else:
        return 0
def filterreg(s):
    index = re.findall(r'[.|\?|!]', s)
    if len(index) != 0:
        return rreplace("", index[-1], 1)
    return s
#从下方修剪出一个完整的句子
def findnext(n, remain, runs):  # 找到含有终结符的run，返回run的index，传入remain 并返回    传入n当前run——id   remain 用于保存
    for i in range(n + 1, len(runs)):
        temp = splitbyreg(runs[i].text)
        if temp == 0:
            if len(remain)==0 or len(runs[i].text)==0:
                pass
            elif remain[-1] == ' ' or runs[i].text[0] == ' ':
                pass
            else:
                # 前后没有间隔  直接从前后run里拉
                if remain != "":
                    te = remain.split(' ')[-1]
                    remain.rstrip()
                    remain = rreplace(remain, te, 1)
                    remain.rstrip()
                    te = te.replace(reg, '', 1)
                    s = "".join(runs[i - 1].text.rsplit(te, 1))
                    runs[i - 1].text = s.strip()
                    runs[i].text = te + runs[i].text
                else:
                    continue
            remain += reg  #
            remain += runs[i].text
            continue
        else:
            if len(remain)==0:
                pass
            elif remain[-1] == " " or runs[i].text[0] == " ":
                pass
            else:
                # 前后没有间隔  直接从前后run里拉
                te = remain.split(' ')[-1]
                runs[i].text = te + runs[i].text
                try:
                    runs[i - 1].text = rreplace(runs[i - 1].text, te, 1)
                except:
                    try:
                        runs[i - 2].text = runs[i - 2].text + runs[i - 1].text
                        runs[i - 1].text = ""
                        runs[i - 2].text = rreplace(runs[i - 2].text, te, 1)

                    except:
                        runs[i - 3].text = runs[i - 3].text + runs[i - 2].text
                        runs[i - 2].text = ""
                        runs[i - 3].text = rreplace(runs[i - 3].text, te, 1)

                temp[0] = te + temp[0]
                remain.rstrip(' ')
                remain = rreplace(remain, te, 1)
                remain.rstrip(' ')
            remain += reg  #
            remain += temp[0]
            # delete
            templist = splitbyreg(runs[i].text)
            if templist==0:
                ast = runs[i].text
            else:
                ast = templist[0]
            m = runs[i].text
            if ast=="" or ast == " " or ast == "   ":
                s = m
            else:
                s = ''.join(m.split(ast, 1))
            runs[i].text = s[1:]
            return [i, remain, runs]
    return [len(runs) - 1, remain, runs]

def find_left(sub, s, ind):#往左唯一几个距离
    index_list = find_all(sub, s)
    index_list.reverse()
    for i in copy.deepcopy(index_list):
        if i >= ind:
            index_list.remove(i)
    return index_list

def find_all(sub, s,index=0):
    index_list = []
    index = s.find(sub, index)
    while index != -1:
        index_list.append(index)
        index = s.find(sub, index + 1)
    if len(index_list) > 0:
        return index_list
    else:
        return []

import jieba
import copy
def funcnext(chremain, n, indext, left, runs, httpClient):
    chremain.strip()
    #log = [-1, 0]*(index-n-1)#every item is structed by [start_index,length]
    unselect = list(range(len(chremain)))
    prefill_l = []
    for i in range(n, indext):#最后一项由left实现
        eng = runs[i].text.strip()
        if len(eng) == 0:
            prefill_l.append([-1, 0])
            continue
        temp = opredict(runs[i].text.strip(), httpClient)
        temp_l = jieba.cut(temp, cut_all=False)
        min_s = 100
        max_s = 0
        #寻找置信区间
        for token in temp_l:
            if len(token) < 2:
                continue
            else:
                loc_l = find_all(token, chremain, max_s)
                for index in loc_l:
                    if listisin(range(index, index + len(token)), unselect):
                        for t in range(index, index + len(token)):
                            unselect.remove(t)
                        if min_s > index:
                            for t in range(index+1, min_s):
                                if t in unselect:
                                    unselect.remove(t)

                            min_s = index
                        if max_s < index + len(token):
                            for t in range(max_s, index + len(token)):
                                if t in unselect:
                                    unselect.remove(t)
                            max_s = index + len(token)
                        unselect.sort()
                        break
                else:  # 没有 ->跳出  没找到 往左找
                    loc_l = find_left(token, chremain, min_s)
                    for index in loc_l:
                        if listisin(range(index, index + len(token)), unselect):
                        #if set(range(index, index + len(token))).issubset(set(copy.deepcopy(unselect))):
                            for t in range(index, index + len(token)):
                                unselect.remove(t)
                        if min_s > index:
                            for t in range(index + 1, min_s):
                                if t in unselect:
                                    unselect.remove(t)

                            min_s = index
                        if max_s < index + len(token):
                            for t in range(max_s, index + len(token)):
                                if t in unselect:
                                    unselect.remove(t)
                            max_s = index + len(token)
                            unselect.sort()
                        else:
                            continue
                        #prefill_l.append([-1, 0])
                    else:
                        continue
                continue
        #找到一个区间/区间没有变化  添加对应项
        if min_s >= max_s:
            prefill_l.append([-1, 0])
        else:
            prefill_l.append([min_s, max_s])

    #进一步处理   left后处理
    #文字写入+写入
    long = len(prefill_l)
        #语序排序
    for ij in range(long):
        if prefill_l[ij][0] == -1:
            continue
        for ik in range(long - ij - 1):
            if prefill_l[ik][0] > prefill_l[ik+1][0]:
                # runs[ik + n], runs[ik + n+1] = runs[ik + n+1], runs[ik + n]
                exchangerunformat(runs[ik + n], runs[ik + n+1])
                prefill_l[ik+1], prefill_l[ik] = prefill_l[ik], prefill_l[ik+1]
#词汇填充后处理算法
    end_index = -1
    cache = 0
    end = 0
    for idl in range(long):
        if prefill_l[idl] == [-1, 0]:
            if end_index == -1:
                end_index = idl
            cache += 1
        elif cache == 0:
            if end == prefill_l[idl][0]:
                end = prefill_l[idl][1]
                runs[n+idl].text = chremain[prefill_l[idl][0]:prefill_l[idl][1]]
            else:
                prefill_l[idl][0] = end
                runs[idl+n].text = chremain[end:prefill_l[idl][1]]#+runs[idl+n].text
                end = prefill_l[idl][1]
        else:#处理前期缓存
            indexit = prefill_l[idl][0]-end
            indexit = indexit/cache
            indexit = int(indexit)
            for i in range(cache-1):
                runs[end_index+n+i].text = chremain[end+i*indexit:end+i*indexit+indexit]
            runs[n+idl-1].text = chremain[end+cache*indexit-indexit:prefill_l[idl][0]]
            runs[n + idl].text = chremain[prefill_l[idl][0]:prefill_l[idl][1]]
            end_index = -1
            cache = 0
            end = prefill_l[idl][1]
    if cache!=0:
        indexit = len(chremain) - end
        indexit = indexit / cache
        indexit = int(indexit)
        for i in range(cache-1):
            runs[end_index + n + i].text = chremain[end + i * indexit:end + i * indexit + indexit]
        runs[n + long- 1].text = chremain[end + cache * indexit - indexit:]
        prefill_l[-1][1] = len(chremain)-1
    runs[n].text = left+runs[n].text
    #格式提取和排序
    ti = 0
    for l in prefill_l:
        if l[1] > ti:
            ti = l[1]
    left = chremain[ti:]+"。"
    return [left, runs]


def listisin(sub, s):
    st = copy.deepcopy(s)
    for i in sub:
        temp = -1
        try:
            temp = st.index(i)
            st.pop(temp)
        except:
            return False
    return True

def exchangerunformat(run1, run2):
    run1.bold,run2.bold=run2.bold,run1.bold
    run1.italic, run2.italic = run2.italic, run1.italic
    run1.style, run2.style = run2.style, run1.style
    run1.underline, run2.underline = run2.underline, run1.underline

    # run2.font.all_caps, run1.font.all_caps = run1.font.all_caps, temp.all_caps
    run2.font.all_caps, run1.font.all_caps = run1.font.all_caps, run2.font.all_caps
    # run2.font.bold, run1.font.bold = run1.font.bold, temp.bold
    run2.font.bold, run1.font.bold = run1.font.bold, run2.font.bold
    # run2.font.cs_italic, run1.font.cs_italic = run1.font.cs_italic, temp.cs_italic
    run2.font.cs_italic, run1.font.cs_italic = run1.font.cs_italic, run2.font.cs_italic
    # run2.font.cs_bold, run1.font.cs_bold = run1.font.cs_bold, temp.cs_bold
    run2.font.cs_bold, run1.font.cs_bold = run1.font.cs_bold, run2.font.cs_bold
    # run2.font.double_strike, run1.font.double_strike = run1.font.double_strike, temp.double_strike
    run2.font.double_strike, run1.font.double_strike = run1.font.double_strike, run2.font.double_strike
    # run2.font.emboss, run1.font.emboss = run1.font.emboss, temp.emboss
    run2.font.emboss, run1.font.emboss = run1.font.emboss, run2.font.emboss
    # run2.font.hidden, run1.font.hidden = run1.font.hidden, temp.hidden
    run2.font.hidden, run1.font.hidden = run1.font.hidden, run2.font.hidden
    # run2.font.highlight_color, run1.font.highlight_color = run1.font.highlight_color, temp.highlight_color
    run2.font.highlight_color, run1.font.highlight_color = run1.font.highlight_color, run2.font.highlight_color
    # run2.font.italic, run1.font.italic = run1.font.italic, temp.italic
    run2.font.italic, run1.font.italic = run1.font.italic, run2.font.italic
    # run2.font.imprint, run1.font.imprint = run1.font.imprint, temp.imprint
    run2.font.imprint, run1.font.imprint = run1.font.imprint, run2.font.imprint
    # run2.font.math, run1.font.math = run1.font.math, temp.math
    run2.font.math, run1.font.math = run1.font.math, run2.font.math
    # run2.font.name, run1.font.name = run1.font.name, temp.name
    run2.font.name, run1.font.name = run1.font.name, run2.font.name
    # run2.font.no_proof, run1.font.no_proof = run1.font.no_proof, temp.no_proof
    run2.font.no_proof, run1.font.no_proof = run1.font.no_proof, run2.font.no_proof
    # run2.font.outline, run1.font.outline = run1.font.outline, temp.outline
    run2.font.outline, run1.font.outline = run1.font.outline, run2.font.outline
    # run2.font.rtl, run1.font.rtl = run1.font.rtl, temp.rtl
    run2.font.rtl, run1.font.rtl = run1.font.rtl, run2.font.rtl
    # run2.font.shadow, run1.font.shadow = run1.font.shadow, temp.shadow
    run2.font.shadow, run1.font.shadow = run1.font.shadow, run2.font.shadow
    # run2.font.size, run1.font.size = run1.font.size, temp.size
    run2.font.size, run1.font.size = run1.font.size, run2.font.size
    # run2.font.small_caps, run1.font.small_caps = run1.font.small_caps, temp.small_caps
    run2.font.small_caps, run1.font.small_caps = run1.font.small_caps, run2.font.small_caps
    # run2.font.snap_to_grid, run1.font.snap_to_grid = run1.font.snap_to_grid, temp.snap_to_grid
    run2.font.snap_to_grid, run1.font.snap_to_grid = run1.font.snap_to_grid, run2.font.snap_to_grid
    # run2.font.spec_vanish, run1.font.spec_vanish = run1.font.spec_vanish, temp.spec_vanish
    run2.font.spec_vanish, run1.font.spec_vanish = run1.font.spec_vanish, run2.font.spec_vanish
    # run2.font.strike, run1.font.strike = run1.font.strike, temp.strike
    run2.font.strike, run1.font.strike = run1.font.strike, run2.font.strike
    # run2.font.subscript, run1.font.subscript = run1.font.subscript, temp.subscript
    run2.font.subscript, run1.font.subscript = run1.font.subscript, run2.font.subscript
    # run2.font.superscript, run1.font.superscript = run1.font.superscript, temp.superscript
    run2.font.superscript, run1.font.superscript = run1.font.superscript, run2.font.superscript
    # run2.font.underline, run1.font.underline = run1.font.underline, temp.underline
    run2.font.underline, run1.font.underline = run1.font.underline, run2.font.underline
    # run2.font.web_hidden, run1.font.web_hidden = run1.font.web_hidden, temp.web_hidden
    run2.font.web_hidden, run1.font.web_hidden = run1.font.web_hidden, run2.font.web_hidden
    # run2.font.complex_script, run1.font.complex_script = run1.font.complex_script, run2.font.complex_script
    run2.font.complex_script, run1.font.complex_script = run1.font.complex_script, run2.font.complex_script

    run2.font.color.rgb, run1.font.color.rgb = run1.font.color.rgb, run2.font.color.rgb
    run2.font.color.theme_color, run1.font.color.theme_color = run1.font.color.theme_color, run2.font.color.theme_color
    pass

def generatecode():
    import random
    import base64
    import io
    import os
    import string
    from PIL import Image, ImageFont, ImageDraw
    # 新建一个图层
    im = Image.new('RGB', (102, 30), 'white')
    # 加载默认字体
    font = ImageFont.load_default()
    # 获取draw对象
    draw = ImageDraw.Draw(im)
    # 设置随机4位数字验证码
    code = ''.join(random.sample(string.digits, 4))
    # 随机颜色
    random_color = lambda: (random.randint(32, 127),
                            random.randint(32, 127),
                            random.randint(32, 127))
    print(code)
    # 将数字输出到图片
    for item in range(4):
        draw.text(
            (6 + random.randint(-3, 3) + 10 * item,
             2 + random.randint(-2, 2)),
            text=code[item], fill=random_color(), font=font)
    # 保存图片
    im.resize((200, 90))
    # if os.path.exists("../web-core/static/code/"+path_name+".jpeg"):
    #     os.remove("../web-core/static/code/"+path_name+".jpeg")
    # im.save("../web-core/static/code/"+path_name+".png", format="JPEG")
    buffered = io.BytesIO()
    im.save(buffered, format="JPEG")
    img_str = b"data:image/png;base64," + base64.b64encode(buffered.getvalue())
    return code, img_str
